package com.kyc.kycxkplaygame.service;

import android.app.Service;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import com.kyc.kycxkplaygame.R;

import java.io.IOException;
import java.util.Random;

/**
 * Created by Administrator on 2018/6/13.
 */

public class MusicBgService extends Service {

    public static final int TILI_ADD = 111;
    public static final int TILI_NOADD = 112;
    int tl = 0;
    private MediaPlayer mPlayer;

    public int[] mBgMusic = {R.raw.m_bg1,R.raw.m_bg2};

    public class MusicBgBinder extends Binder {
        // 声明一个方法，getService。（提供给客户端调用）
        MusicBgService getService() {
            // 返回当前对象LocalService,这样我们就可在客户端端调用Service的公共方法了
            return MusicBgService.this;
        }
    }

    public Handler handler = new Handler();


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicBgBinder();
    }

    @Override
    public void onCreate() {
        mPlayer = new MediaPlayer();
        //play();
    }

    public void play(){
        Random random = new Random();
        int nextInt = random.nextInt(1)+1;
        Log.i("KYCC","nextInt   ==== "+nextInt);
        AssetFileDescriptor file = getResources().openRawResourceFd(mBgMusic[nextInt]);
        try {
            mPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
                    file.getLength());
            mPlayer.prepare();
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mPlayer.start();
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                play();
            }
        });
    }

    public void pause(){
        mPlayer.pause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPlayer.stop();
        mPlayer.release();
    }
}
